package com.cardvalue.sys.mode;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.preference.DialogPreference;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.alibaba.fastjson.JSON;
import com.cardvalue.sys.activity.ForgetPasswordActivity;
import com.cardvalue.sys.activity.HomeActivity;
import com.cardvalue.sys.activity.LoginActivity;
import com.cardvalue.sys.cache.LocalCache;
import com.cardvalue.sys.dialog.IosDailog;
import com.cardvalue.sys.entity.Apply;
import com.cardvalue.sys.entity.Credit;
import com.cardvalue.sys.entity.Login;
import com.cardvalue.sys.entity.PostCreateAuth;
import com.cardvalue.sys.entity.User;
import com.cardvalue.sys.newnetwork.Config;
import com.cardvalue.sys.tool.LocationUtil;
import com.cardvalue.sys.tool.MD5Util;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.Date;
import java.util.Map;

import cn.fraudmetrix.android.FMAgent;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 注册相关的
 * Created by cardvalue on 2016/4/13.
 */
public class RegService {
    private Retrofit retrofit;
    private  UserService  userService;//获取用户
    private Service.LoginService service;//登录
    private Service.Register    registerService;//注册
    private Service.CreateAuthorization CreateAuthService;//创建授权
    private Context context;
    public RegService(Context context){
        this.context=context;
        userService=new UserService(context);
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.getServerIp())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }



    /**
     * 创建授权
     * @param mobile  //手机号码
     *  @param  pass//加密后的密码
     * @param isLogin  //判断传入进来的isLogin值，如果是isLogin的话，就是下面要登录的操作，
     *                 负责，注册
     * @throws Exception
     */
    public void attemptCreateAuthorization(final String mobile, final String pass, final String pushId , final String verifyCode, final String ip, final String isLogin){
        CreateAuthService=retrofit.create(Service.CreateAuthorization.class);
        PostCreateAuth postCreateAuth=new PostCreateAuth();
        WebView webview = new WebView(context);
        webview.layout(0, 0, 0, 0);
        WebSettings settings = webview.getSettings();
        String ua = settings.getUserAgentString();
        Map<String,String> map= LocationUtil.getMap();
        postCreateAuth.setMobilePhone(mobile);//手机号码
        postCreateAuth.setAgent(ua);//浏览器的User-Agent (UA) 字符串
        postCreateAuth.setDeviceNumber(map.get("imel")==null?"":map.get("imel").toString());//设备号
        postCreateAuth.setGps(map.get("ongitude")+","+map.get("atitude"));//经纬度
        postCreateAuth.setType(5);//5：同意注册条款、申请条款、确认放款条款和征信报告协议
        postCreateAuth.setIp("");//
        postCreateAuth.setTime(new Date().toLocaleString());
        Utiltools.printE("postCreateAuth==",postCreateAuth.getMobilePhone());
        Call<PostCreateAuth> call = CreateAuthService.attemptCreateAuthorization(postCreateAuth);
        call.enqueue(new Callback<PostCreateAuth>() {
            @Override
            public void onResponse(Call<PostCreateAuth> call, Response<PostCreateAuth> response) {
                PostCreateAuth CreateAuth=response.body();
                Log.e("创建授权=duanjie==objectId",CreateAuth.getObjectid()+"");
                Log.e("创建授权2===objectId",CreateAuth.getCreatedAt()+"");
                String error=CreateAuth.getError()+"";
                if(!error.equals("null")){
                    MessageBox.ToastShow(CreateAuth.getError()+"",context);
                    return;
                }

                if(!isLogin.equals("isLogin")){//注册之前没有授权，所以授权之后登录
                    Log.e("创建授权=====",mobile+"==SH==="+verifyCode+"==验证码=="+pass);
                        register(mobile,pass,pushId,verifyCode,ip);
                }
            }

            @Override
            public void onFailure(Call<PostCreateAuth> call, Throwable t) {

            }
        });
    }

    /**
     * 注册接口
     */
    public void register(final String mobile, final String pass, final String pusdId, String verifyCode, String ipAddress){
        registerService=retrofit.create(Service.Register.class);
        String blackBox = FMAgent.onEvent();
        Login reg=new Login();
        reg.setMobilePhone(mobile); //手机号码
        String  pass1=MD5Util.MD5(pass);
        reg.setPassword(pass1);//密码
        reg.setPushId(pusdId);//推送的id
        reg.setType("1");//1 是注册   2是忘记密码
        reg.setMobilePhoneVerifyCode(verifyCode);//短信验证码
        reg.setIpAddress(ipAddress);//ip地址
        reg.setBlackBox(blackBox);//同盾
        Call<Login> repos=registerService.attempRegister(reg);
        repos.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {
                Login reg=response.body();
                String error=reg.getError()+"";
                if(!error.equals("null")){
                    MessageBox.ToastShow(reg.getError()+"",context);
                    return;
                }
                Log.e("注册===",reg.getObjectId()+"==accessToken="+ reg.getAccessToken()+"");
                Login(mobile,pass,pusdId);
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {

            }
        });
    }


    /**
     * 修改密码
     */
    public void forgetPassword(final String mobile, final String pass, final String pusdId, String verifyCode, String ipAddress){
        registerService=retrofit.create(Service.Register.class);
        String blackBox = FMAgent.onEvent();
        Login reg=new Login();
        reg.setMobilePhone(mobile); //手机号码
        String  pass1=MD5Util.MD5(pass);
        reg.setPassword(pass1);//密码
        reg.setPushId(pusdId);//推送的id
        reg.setType("2");//1 是注册   2是忘记密码
        reg.setMobilePhoneVerifyCode(verifyCode);//短信验证码
        reg.setIpAddress(ipAddress);//ip地址
        reg.setBlackBox(blackBox);//同盾
        Call<Login> repos=registerService.attempRegister(reg);
        repos.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {
                Login reg=response.body();
                String error=reg.getError()+"";
                if(!error.equals("null")){
                    MessageBox.ToastShow(reg.getError()+"",context);
                    return;
                }
            //弹出dialog
                IosDailog.CustomAlert("修改成功", "您的密码已经修改成功，是否进行登陆?",context, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        context.startActivity(new Intent(context,LoginActivity.class));
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {

            }
        });
    }


    /**
     * 登录接口
     * @param mobile
     * @param pass
     */
    public  void Login(String mobile,String pass,String pushId){
        service = retrofit.create(Service.LoginService.class);
        long data=System.currentTimeMillis()/1000;
        String pass1= MD5Util.MD5(MD5Util.MD5(pass)+"cvbaoli"+data)+"|"+data;
        Call<Login> repos = service.attemptLogin(mobile,pass1);
        repos.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {
                Login login=response.body();
                String error=login.getError()+"";
                if(!error.equals("null")){
                    MessageBox.ToastShow(login.getError()+"",context);
                    return;
                }
                LocalCache.saveDataToLocal(context,"objectId",login.getObjectId());
                LocalCache.saveDataToLocal(context,"accessToken",login.getAccessToken());
                LocalCache.getStringLocalData(context,"objectId");
                LocalCache.getStringLocalData(context,"accessToken");
                afterLogin();
               // context.startActivity(new Intent(context,HomeActivity.class));
            }
            @Override
            public void onFailure(Call<Login> call, Throwable t) {

            }
        });
    }



    /**
     * 登录要调用的接口   获取用户    获取最新申请
     * 获取最新授信额度  获取系统消息  正在获取用户消息
     * 正在获取红包  获取商户列表
     */

    public void   afterLogin(){
        userService.getGetUserInfo(LocalCache.getStringLocalData(context, "objectId"), new UserService.UsesrCallback() {//获取用户
            @Override
            public void success(User user) {

                Utiltools.printE("tag获取最新的申请user===", JSON.toJSONString(user)+"====");
                LocalCache.saveDataToLocal(context,"applicationId",user.getApplicationId());//保存applicationId到缓存
                userService.latesApplication(new UserService.GetApplyCallback() {//获取最新的申请
                    @Override
                    public void success(Apply applyInfo) {
                        Utiltools.printE("tag获取最新的申请apply===", JSON.toJSONString(applyInfo)+"====");
                        if(!TextUtils.isEmpty(applyInfo.getCreditId())){//CreditId()不等于空，就直接获取授信
                            userService.getCreditLimitService(applyInfo.getCreditId(), new UserService.GetCreditCallback() {//获取授信
                                @Override
                                public void success(Credit creditLimit) {
                                    context.startActivity(new Intent(context,HomeActivity.class));
                                }

                                @Override
                                public void fail(String msg) {

                                }

                                @Override
                                public void cancelDialog() {

                                }
                            });
                        }else{//  获取系统消息   正在获取用户消息   正在获取红包   获取商户列表   到最后跳转
                            context.startActivity(new Intent(context,HomeActivity.class));
                        }





                    }

                    @Override
                    public void fail(String msg) {

                    }

                    @Override
                    public void cancelDialog() {

                    }
                });
                //startActivity(new Intent(LoginActivity.this,HomeActivity.class));
            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {

            }
        });
    }
}
